package com.wry.wry_test.algorithm;

import java.sql.PreparedStatement;

public class Day1 {

    public static void main(String[] args) {
        Day1 day1 = new Day1();
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode result = day1.addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }


    //https://leetcode.cn/problems/add-two-numbers/
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode tail = null;

        while (l1 != null && l2 != null) {
            ListNode result = new ListNode();
            if (tail != null) {
                tail.next = result;
            }
            tail = result;
            head = head == null ? result : head;
            int sum = l1.val + l2.val;
            if (sum >= 10) {
                if (l1.next != null) {
                    l1.next.val++;
                } else if (l2.next != null) {
                    l2.next.val++;
                } else {
                    result.next = new ListNode(1);
                }
            }
            result.val = sum % 10;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null && tail != null) {
            ListNode result = new ListNode();
            tail.next = result;
            tail = result;
            l1 = l1.next;
        }
        while (l2 != null && tail != null) {
            ListNode result = new ListNode();
            tail.next = result;
            tail = result;
            l2 = l2.next;
        }

        return head;
    }
}
